package com.example.dynamic_form.controller;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.UUID;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("excelTest")
public class ReadExcelImageController {
    @GetMapping("/read")
    public void read(String[] args) {
        String excelPath = "E:\\myWorkSpace\\back-end\\dynamic-form\\file\\BOM-table.xls";
        String savePath = "E:\\myWorkSpace\\back-end\\dynamic-form\\images\\";

        try (FileInputStream fis = new FileInputStream(excelPath);
             HSSFWorkbook workbook = new HSSFWorkbook (fis)) {

            // 获取第一个工作表
            HSSFSheet sheet = workbook.getSheetAt(0);
            HSSFPatriarch drawing = sheet.getDrawingPatriarch();

            if (drawing != null) {
                List<HSSFShape> shapes = drawing.getChildren();
                for (HSSFShape shape : shapes) {
                    if (shape instanceof HSSFPicture) {
                        HSSFPicture picture = (HSSFPicture) shape;
                        HSSFAnchor anchor = picture.getAnchor();
                        HSSFClientAnchor clientAnchor = (HSSFClientAnchor) anchor;
                        int row = clientAnchor.getRow1();
                        int col = clientAnchor.getCol1();
                        HSSFPictureData pictureData = picture.getPictureData();
                        byte[] data = pictureData.getData();

                        // 保存图片到本地
                        String ext = pictureData.suggestFileExtension();
                        String fileName = savePath + row + "行" + col + "列" + "." + ext;
                        try (FileOutputStream fos = new FileOutputStream(fileName)) {
                            fos.write(data);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
